package vip.zhy.faststart.framework.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import vip.zhy.faststart.framework.domain.Response;
import vip.zhy.faststart.framework.jwt.Jwt;

import java.io.PrintWriter;

@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {

    public static final String TOKEN_NAME = "Authorization";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader(TOKEN_NAME);
        boolean flag = Jwt.parseToken(token);
        if (!flag) {
//            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            PrintWriter writer = response.getWriter();
            writer.println(Response.unauthorized());
            writer.flush();
        }
        return flag;
    }

}
